<!--
 * @Author: zhoulei0232
 * @Date: 2023-04-01 23:03:20
 * @LastEditTime: 2023-04-14 01:21:01
 * @LastEditors: zhoulei0232
 * @Description: 
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="用户名" prop="queryUserName">
        <el-input
          v-model="queryParams.queryUserName"
          placeholder="搜索用户名"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发帖内容" prop="queryContent">
        <el-input
          v-model="queryParams.queryContent"
          placeholder="搜索发帖内容"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="queryApprove">
        <el-select
          v-model="queryParams.queryApprove"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="dict in approveStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="multiple"
          @click="handleAllApprove"
          v-hasPermi="['business:invitation:edit']"
          >批量审核</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:invitation:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="pageList"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="100" />
      <el-table-column label="发帖图片" align="center" prop="src" width="400">
        <template #default="scope">
          <div class="invitation-image-list">
            <div v-for="(item, index) in scope.row.imagesList" :key="index">
              <el-image
                :key="index"
                style="width: 100px; height: 100px"
                :src="uploadShowUrl + item"
                :preview-teleported="true"
                :preview-src-list="[uploadShowUrl + item]"
                fit="contain"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="发帖人"
        align="center"
        prop="username"
        width="150"
      />
      <el-table-column
        label="标题"
        align="center"
        prop="title"
        width="250"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="内容"
        align="center"
        prop="content"
        width="450"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="发帖类型" align="center" prop="type" width="100">
        <template #default="scope">
          <dict-tag :options="typeList" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column
        label="审核状态"
        align="center"
        prop="approve"
        width="100"
      >
        <template #default="scope">
          <dict-tag :options="approveStatusList" :value="scope.row.approve" />
        </template>
      </el-table-column>

      <el-table-column label="置顶" align="center" prop="top">
        <template #default="scope">
          <el-switch
            v-model="scope.row.top"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="加精" align="center" prop="classics">
        <template #default="scope">
          <el-switch
            v-model="scope.row.classics"
            active-value="1"
            inactive-value="0"
            @change="handleClassicsChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="发帖日期"
        align="center"
        prop="createdAt"
        width="250"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createdAt, "{y}-{m}-{d}  {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleApprove(scope.row)"
            v-hasPermi="['business:invitation:edit']"
            >审核</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:invitation:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="审核意见" prop="approve">
              <el-radio-group v-model="form.approve">
                <el-radio
                  v-for="dict in approveList"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.approve === '0'">
            <el-form-item label="驳回原因" prop="remark">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入驳回原因"
                v-model="form.remark"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="debouncedFn">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Invitation">
import {
  listInvitation,
  approveInvitation,
  updateInvitation,
  deleteInvitation,
} from "@/api/business/invitation";

import { useDebounceFn } from "@vueuse/core";

const { proxy } = getCurrentInstance();
// 图片上传地址
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + "api/uploadCos/goods";
const uploadShowUrl = import.meta.env.VITE_APP_COS_API;
const imageUrl = ref("");
const dateRange = ref([]);
const pageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const detailTitle = ref(""); // 详情标题栏

const painterList = ref([]); // 画师下拉框
const approveStatusList = ref([
  {
    label: "已审核",
    value: "1",
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "未审核",
    value: "0",
    elTagClass: "",
    elTagType: "danger",
  },
]);

const typeList = ref([
  {
    label: "求购",
    value: "1",
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "转让",
    value: "2",
    elTagClass: "",
    elTagType: "danger",
  },
]);

const useOtherPlatformList = ref([
  { label: "是", value: "是" },
  { label: "否", value: "否" },
]);

const approveList = ref([
  { label: "通过", value: "1" },
  { label: "不通过", value: "0" },
]);
const openSub = ref(false); // 查看购买详情
const loadingSub = ref(false);
const pageListSub = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    queryUserName: undefined,
    queryContent: undefined,
    queryApprove: undefined,
    queryCtType: "1,2,3,4,5",
  },
  rules: {
    approve: [
      { required: true, message: "审核状态不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/png" && rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be PNG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
function onSuccessImg(response) {
  if (response.code == 200) {
    form.value.src = response.data;
    imageUrl.value = uploadShowUrl + response.data;
  }
}

/** 查询公告列表 */
function getList() {
  loading.value = true;
  listInvitation(proxy.addDateRangeZL(queryParams.value, dateRange.value)).then(
    (response) => {
      pageList.value = response.data.rows.map((item) => {
        let imagesList = [];
        if (item.images) {
          imagesList = item.images.split(",");
        }
        return {
          ...item,
          imagesList: imagesList,
        };
      });

      total.value = response.data.count;
      loading.value = false;
    }
  );
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    approve: undefined,
    remark: undefined,
  };
  imageUrl.value = null;
  proxy.resetForm("noticeRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.queryCtType = "1,2,3,4,5";
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.queryUserName = undefined;
  queryParams.value.queryContent = undefined;
  queryParams.value.queryApprove = undefined;
  queryParams.value.queryCtType = "1,2,3,4,5";
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
}
/** 批量审核按钮操作 */
function handleAllApprove() {
  let approveId = ids.value;

  if (approveId.length === 0) {
    return;
  }
  form.value.id = approveId;
  open.value = true;
  title.value = "批量审批";
}
/**审核按钮操作 */
function handleApprove(row) {
  let approveId = row.id || ids.value;
  if (!Array.isArray(approveId)) {
    approveId = [approveId];
  }
  form.value.id = approveId;
  open.value = true;
  title.value = "审批";
  // proxy.$modal
  //   .confirm('是否确认删除公告编号为"' + deleteId + '"的数据项？')
  //   .then(function () {
  //     return deleteGoods({ id: deleteId });
  //   })
  //   .then(() => {
  //     getList();
  //     proxy.$modal.msgSuccess("删除成功");
  //   })
  //   .catch(() => {});
}
/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  if (!row.id) {
    let arr = pageList.value.filter((item) => {
      return item.id == ids.value;
    });
    form.value = {
      ...arr[0],
      name: arr[0].goodsName,
    };
  } else {
    form.value = {
      ...row,
      name: row.goodsName,
    };
    imageUrl.value = uploadShowUrl + row.src;
  }

  open.value = true;
  title.value = "修改";
}
// 防抖操作
const debouncedFn = useDebounceFn(
  () => {
    submitForm();
  },
  1000,
  { maxWait: 3000 }
);

/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      let sendData = {
        id: form.value.id,
        approve: form.value.approve,
        remark: form.value.remark || "",
      };
      approveInvitation(sendData).then((response) => {
        proxy.$modal.msgSuccess("操作成功！");
        open.value = false;
        getList();
      });
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  let deleteId = row.id || ids.value;
  if (!Array.isArray(deleteId)) {
    deleteId = [deleteId];
  }

  proxy.$modal
    .confirm('是否确认删除公告编号为"' + deleteId + '"的数据项？')
    .then(function () {
      return deleteInvitation({ id: deleteId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

function handleChangeUseRange(params) {
  let arr = useRangeList.value.filter((item) => {
    return item.value == params;
  });
  if (arr && arr.length > 0) {
    return arr[0].label;
  } else {
    return " ";
  }
}
/** 置顶状态修改  */
function handleStatusChange(row) {
  let text = row.top == "1" ? "置顶" : "不置顶";

  proxy.$modal
    .confirm('确认要"' + text + '""' + row.title + '"的数据吗?')
    .then(function () {
      let sendData = {
        id: row.id,
        top: row.top,
      };
      return updateInvitation(sendData);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.top = row.top == "1" ? "0" : "1";
    });
}
/** 加精状态修改  */
function handleClassicsChange(row) {
  let text = row.classics == "1" ? "加精" : "不加精";

  proxy.$modal
    .confirm('确认要"' + text + '""' + row.title + '"的数据吗?')
    .then(function () {
      let sendData = {
        id: row.id,
        classics: row.classics,
      };
      return updateInvitation(sendData);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.classics = row.classics == "1" ? "0" : "1";
    });
}

// 排序
function handleSortChange(column) {
  let data1;
  if (column.order == "ascending") {
    data1 = "ASC";
  } else if (column.order == "descending") {
    data1 = "DESC";
  }
  if (!data1) {
    data.queryParams.orderName = undefined;
  } else {
    data.queryParams.orderName = column.prop;
  }
  data.queryParams.orderType = data1;
  getList();
}
getList();
</script>
<style lang="scss" scoped>
.color-blue {
  color: rgb(0, 119, 255);
  cursor: pointer;
}
.avatar-uploader {
  width: 200px;
  height: 300px;
  .avatar {
    width: 100%;
    height: 100%;
  }
}
.avatar-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.invitation-image-list {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
</style>
